import axiosInstance from './axiosInstance';
import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';

// 获取未读通知
export const getUnreadNotifications = () => {
    return axiosInstance.get('/api/notifications/unread');
};

// 获取所有通知
export const getAllNotifications = () => {
    return axiosInstance.get('/api/notifications/all');
};

// 创建新通知
export const createNotification = (content, type) => {
    const formData = new URLSearchParams();
    formData.append('content', content);
    formData.append('type', type);
    return axiosInstance.post('/api/notifications', formData);
};

// 标记通知为已读
export const markNotificationAsRead = (notificationId) => {
    return axiosInstance.put(`/api/notifications/${notificationId}/read`);
};

// 删除通知
export const deleteNotification = (notificationId) => {
    return axiosInstance.delete(`/api/notifications/${notificationId}`);
};

// 获取特定通知
export const getNotification = (notificationId) => {
    return axiosInstance.get(`/api/notifications/${notificationId}`);
};

// 创建并广播通知（管理员使用）
export const createAndBroadcastNotification = async (content, type) => {
    try {
        const response = await axiosInstance.post('/api/notifications/admin/broadcast', { content, type });
        return response.data;
    } catch (error) {
        throw new Error(error.response ? error.response.data.message : error.message);
    }
};

let stompClient = null;

export const setupWebSocket = (onMessage) => {
    if (stompClient) {
        return {
            disconnect: () => {
                if (stompClient && stompClient.connected) {
                    stompClient.disconnect(() => {
                        console.log('WebSocket连接已关闭');
                    });
                }
                stompClient = null;
            }
        };
    }

    const socket = new SockJS('http://localhost:8080/ws');
    stompClient = Stomp.over(socket);

    const headers = {};
    const token = localStorage.getItem('auth_token');
    if (token) {
        headers['Authorization'] = token;
    }

    stompClient.connect(headers, frame => {
        console.log('WebSocket连接已成功建立:', frame);
        
        // 订阅个人通知
        stompClient.subscribe(`/user/topic/notifications`, message => {
            console.log('收到个人WebSocket消息:', message.body);
            const notification = JSON.parse(message.body);
            onMessage(notification);
        });

        // 订阅全局通知
        stompClient.subscribe('/topic/notifications/all', message => {
            console.log('收到全局WebSocket消息:', message.body);
            const notification = JSON.parse(message.body);
            onMessage(notification);
        });
    }, error => {
        console.error('WebSocket错误:', error);
    });

    return {
        disconnect: () => {
            if (stompClient && stompClient.connected) {
                stompClient.disconnect(() => {
                    console.log('WebSocket连接已关闭');
                });
            }
            stompClient = null;
        }
    };
};

// 发送新通知（管理员使用）
export const sendNotification = (content, type) => {
    if (!stompClient) {
        console.error('WebSocket未连接');
        return;
    }
    const notification = { content, type };
    stompClient.send("/app/notification", {}, JSON.stringify(notification));
};